package com.lee.boot.head.first.demo.controller;

import org.springframework.beans.propertyeditors.CustomDateEditor;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.InitBinder;
import org.springframework.web.bind.annotation.ModelAttribute;

import java.io.FileNotFoundException;
import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * @Description: 注解@ControllerAdvice中的basePackages和annotations都是控制注解扫描的范围，两者同时存在会取并集
 * @author: Lee
 * @Date: 2019/11/23
 */
@ControllerAdvice(basePackages = "com.lee.springboot.web.controller", annotations = Controller.class)
public class AdviceControllerConfig {

    /**
     * @Description: 在controller方法执行前执行。
     * 绑定格式化，参数转换规则，和验证器等配置
     * @Param:
     * @Return :
     * @author: Lee
     * @Date: 2019/11/23
     */
    @InitBinder
    public void initBinder(WebDataBinder webDataBinder) {
        CustomDateEditor customDateEditor = new CustomDateEditor(new SimpleDateFormat("yyyy-MM-dd"), false);
        webDataBinder.registerCustomEditor(Date.class, customDateEditor);

    }

    /**
     * @Description: 在controller方法之前执行，可以给model中提前添加属性
     * @author: Lee
     * @Date: 2019/11/23
     */
    @ModelAttribute
    public void modelAttribute(Model model) {
        model.addAttribute("id", "user_id");
    }

    @ExceptionHandler(FileNotFoundException.class)
    public String pathNotfoundException(Model model, FileNotFoundException e) {
        // 给返回的数据模型中添加错误提示信息
        model.addAttribute("exception_info", "not found file ");
        // 也可以直接返回视图
        return "";
    }


}
